package day20210127;

import org.junit.Test;

/*
* 13. 罗马数字转正数
* */
public class RomanNumeralToPositive {
    /* 第一种做法：有错误，实现的复杂 */
    @Test
    public void test01() {
        String x = "IX" ;
        int y = 0 ;
        switch (x) {
            case "IV" :
                y = 4 ;
                break;
            case "IX" :
                y = 9 ;
                break;
            case "XL" :
                y = 40 ;
                break;
            case "XC" :
                y = 90 ;
                break;
            case "CD" :
                y = 400 ;
                break;
            case "CM" :
                y = 900 ;
                break;
            default:
                char[] chars = x.toCharArray();
                for (char aChar : chars) {
                    if (aChar == 'I') {
                        y += 1 ;
                    }else if (aChar == 'V' ) {
                        y += 5 ;
                    }else if (aChar == 'X' ) {
                        y += 10 ;
                    }else if (aChar == 'L' ) {
                        y += 50 ;
                    }else if (aChar == 'C' ) {
                        y += 100 ;
                    }else if (aChar == 'D' ) {
                        y += 500 ;
                    }else if (aChar == 'M' ) {
                        y += 1000 ;
                    }
                }
        }
        System.out.println(y);
    }

    /* 第二中做法：通过前后两个数对比，判断得到前一个数的符号是正还是负 */
    @Test
    public void test02() {
        String s = "MCMXCIV";
        int length = s.length() , count = 0 , temp , temp1 = getValue(s.charAt(0)) ;
        for (int i = 1 ; i < length ; i++ ) {
            temp = getValue(s.charAt(i)) ;
            if (temp > temp1 ) {
                temp1 = -temp1;
            }
            count += temp1 ;
            temp1 = temp ;
        }
        // 因为判断的总是前一位数值，所以最好要把最后一位数加上，最后一位数一定是正数
        count += getValue(s.charAt(length-1));
        System.out.println(count);
    }

    private int getValue(char ch) {
        switch(ch) {
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default: return 0;
        }
    }
}
